import gzip

from flask import request


class Gzip:
    def __init__(self, app=None, compress_level=9, minimum_size=500):
        self.app = None
        self.compress_level = compress_level
        self.minimum_size = minimum_size
        if app:
            self.init_app(app)

    def init_app(self, app):
        self.app = app
        self.app.after_request(self.compress)
        self.app.before_request(self.decompress)

    def compress(self, response):
        accept_encoding = request.headers.get('Accept-Encoding', '')

        if response.status_code < 200 \
                or response.status_code >= 300 \
                or response.direct_passthrough \
                or len(response.data) < self.minimum_size \
                or 'gzip' not in accept_encoding.lower() \
                or 'Content-Encoding' in response.headers:
            return response

        response.set_data(gzip.compress(response.data, compresslevel=self.compress_level))
        response.headers['Content-Encoding'] = 'gzip'
        return response

    @staticmethod
    def decompress():
        if request.headers.get('Content-Encoding') == 'gzip':
            decompressed = gzip.decompress(request.get_data())
            request._cached_data = decompressed.decode('utf-8')
